package com.module.circle.ui.schedule

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.LinearLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppBackPressedFragment
import com.common.app.core.RouterHub
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.helper.EventUmengAgent
import com.common.app.helper.UmengAgentHelper
import com.common.app.helper.UserHelper
import com.common.app.widget.mybanner.BannerBean
import com.common.app.widget.mybanner.BannerConfig
import com.common.app.widget.mybanner.GlideImageRoundCompressionLoader
import com.common.app.widget.mybanner.SBanner
import com.common.app.widget.mybanner.listener.OnBannerListener
import com.common.base.adapter.BaseFragmentPageAdapter
import com.common.base.app.activity.BaseVMActivity
import com.common.base.app.extras.loadCircle
import com.common.base.app.extras.loadRound
import com.common.base.app.extras.no
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.startActivityResultLauncher
import com.common.base.utils.AppUtils.getColor
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.StatusBarUtils.setStatusBarHeight
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.dp2px
import com.common.base.utils.ViewUtils.sp2px
import com.common.base.widget.indicators.SScaleTransitionPagerTitleView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.circle.R
import com.module.circle.databinding.CircleFragmentMainBinding
import com.module.circle.ui.changeIntroduction.ChangeMyIntroductionActivity
import com.module.circle.ui.createCircle.CreateCircleActivity
import com.module.circle.ui.msgNotifications.MsgNotificationsListActivity
import com.module.circle.ui.myMedal.MyMedalActivity
import me.yokeyword.fragmentation.SupportActivity
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：28/6/2029
 * <p>
 * 描述：圈子首页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_CIRCLE_FRAGMENT)
class CircleFragment : AppBackPressedFragment<CircleFragmentMainBinding, CircleViewModel>(),
    View.OnClickListener, OnBannerListener {

    override fun getViewModel() = CircleViewModel::class.java

    override fun getViewBinding() = CircleFragmentMainBinding.inflate(layoutInflater)

    val titles = ArrayList<String>()

    private var modifyNoteLauncherResult: ActivityResultLauncher<Intent>? = null

    override fun initViews() {
        super.initViews()
        setStatusBarHeight(mViewBinding.statusView)

//        mViewBinding.totalBanner.setPadding(ViewUtils.dp2px(10),0,ViewUtils.dp2px(10), 0)
        mViewBinding.banner.apply {
            removeIndicator()
            setIndicatorGravity(BannerConfig.CENTER)
            setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
            initBanner(this)
        }


        titles.add(getString(R.string.circle_recommendation_circle_hint))
        titles.add(getString(R.string.circle_my_circle_hint))

        val mFragments = arrayListOf<Fragment>()

        for (i in titles) mFragments.add(CircleListSubFragment.newInstance(i))


        val mAdapter = BaseFragmentPageAdapter(childFragmentManager, mFragments, titles)
        mViewBinding.viewPager.adapter = mAdapter
        mViewBinding.viewPager.offscreenPageLimit = mFragments.size
        mAdapter.setNoDestroy(0, 1)

        initMagicIndicator()
    }

    override fun lazyInitData() {
        super.lazyInitData()

        val bannerData = mutableListOf<BannerBean>()
        bannerData.add(
            BannerBean(
                "1",
                1,
                "",
                "https://iknow-pic.cdn.bcebos.com/d788d43f8794a4c2e698f6b51cf41bd5ac6e39f0?for=bg",
                "",
                "",
                0,
                "",
                "https://iknow-pic.cdn.bcebos.com/d788d43f8794a4c2e698f6b51cf41bd5ac6e39f0?for=bg",
                "",
                false
            )
        )
        bannerData.add(
            BannerBean(
                "1",
                1,
                "",
                "https://img2.baidu.com/it/u=2533628581,1831602009&fm=253&app=120&f=JPEG?w=1422&h=800",
                "",
                "",
                0,
                "",
                "https://img2.baidu.com/it/u=2533628581,1831602009&fm=253&app=120&f=JPEG?w=1422&h=800",
                "",
                false
            )
        )
        bannerData.add(
            BannerBean(
                "1",
                1,
                "",
                "https://img0.baidu.com/it/u=2282346847,4231483516&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
                "",
                "",
                0,
                "",
                "",
                "",
                false
            )
        )
        mViewBinding.banner.setImages(bannerData)
            .setRoundImageLoader(GlideImageRoundCompressionLoader())
            .setOnBannerListener(this)
            .start()
        mViewBinding.banner.isAutoPlay(false)
        mViewBinding.banner.stopAutoPlay()
        if (bannerData.isNotEmpty() && bannerData.size > 1) {
            mViewBinding.banner.isAutoPlay(true)
            mViewBinding.banner.startAutoPlay()
        }

        setUserData()
    }

    override fun initEvents() {
        super.initEvents()
        modifyNoteLauncherResult = createModifyNoteResultLauncher()

        mViewBinding.btnCreateCircle.setOnClickListener(onClick = this)
        mViewBinding.btnEdt.setOnClickListener(onClick = this)
        mViewBinding.tvMedalNum.setOnClickListener(onClick = this)
        mViewBinding.imgMsgNumBg.setOnClickListener(onClick = this)

        LiveEventBus.get(KeyEvents.KEY_REFRESH_USER_INFO_DATA).observe(this){
            setUserData()
        }
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        StatusBarUtils.setStatusBarForegroundColor(activity, true)
        UmengAgentHelper.onEvent(EventUmengAgent.visit_circle_main)
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
    }


    override fun onClick(v: View?) {
        //防止多次点击
        if (ViewUtils.isFastClick()) return
        when (v) {
            mViewBinding.tvMedalNum->{
                val bundle = Bundle()
                bundle.putInt(
                    KeyBundle.BUNDLE_KEY,
                    UserHelper.getUser()?.user_id?:0
                )
                requireActivity().startActivity<MyMedalActivity>( bundle, false)
            }
            mViewBinding.btnCreateCircle-> requireActivity().startActivity<CreateCircleActivity>(false)
            mViewBinding.btnEdt -> {
                val bundle = Bundle()
                bundle.putString(
                    KeyBundle.BUNDLE_KEY,
                    mViewBinding.tvBriefIntroduction.text.toString()
                )
                requireActivity().startActivityResultLauncher<ChangeMyIntroductionActivity>(modifyNoteLauncherResult, bundle, false)
            }
            mViewBinding.imgMsgNumBg->{
                requireActivity().startActivity<MsgNotificationsListActivity>( false)
            }
        }
    }

    fun setUserData(){
        UserHelper.getUser()?.let {
            mViewBinding.imgHead.loadCircle(it.avatar_url, placeholder = R.drawable.common_logo_icon,2,borderColor = getColor(R.color.white))
            mViewBinding.tvNikeName.text = if(it.nickname.isNullOrEmpty()) it.mobile else it.nickname
            mViewBinding.tvBriefIntroduction.text = it.description

            mViewBinding.tvMedalNum.text = "${it.badge_count}${ViewUtils.getString(R.string.circle_splicing_medal_hint)}"
        }
    }

    private fun initBanner(banner: SBanner) {
        // 头部布局比例16:9(0.56)3:1(0.33)
        val params: ViewGroup.LayoutParams = banner.layoutParams
//        params.height = ((ViewUtils.getScreenWidth() - dp2px(32)) * 0.33).toInt()
        params.height = (ViewUtils.getScreenWidth() / 368f * 108f + 0.5f).toInt()
        banner.layoutParams = params
    }


    private fun initMagicIndicator() {
        val commonNavigator = CommonNavigator(requireActivity())
        commonNavigator.isAdjustMode = true
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val badgePagerTitleView = BadgePagerTitleView(context)
                val simplePagerTitleView = SScaleTransitionPagerTitleView(context)
                simplePagerTitleView.text = titles[index]
                simplePagerTitleView.textSize = 14f
                simplePagerTitleView.normalColor = getColor(R.color.text_content)
                simplePagerTitleView.selectedColor = getColor(R.color.product_color)
                simplePagerTitleView.setOnClickListener {
                    mViewBinding.viewPager.currentItem = index
                    badgePagerTitleView.badgeView = null // cancel badge when click tab
                }
                badgePagerTitleView.innerPagerTitleView = simplePagerTitleView

                // don't cancel badge when tab selected
                badgePagerTitleView.isAutoCancelBadge = false
                return badgePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.lineHeight = UIUtil.dip2px(context, 3.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 24.0).toFloat()
                indicator.roundRadius = UIUtil.dip2px(context, 3.0).toFloat()
//                indicator.yOffset = UIUtil.dip2px(context, 2.0).toFloat()
                indicator.setColors(getColor(R.color.product_color))
                indicator.startInterpolator = AccelerateInterpolator()
                indicator.endInterpolator = DecelerateInterpolator(2.0f)
                return indicator
            }
        }
        mViewBinding.magicIndicator.navigator = commonNavigator
        val titleContainer = commonNavigator.titleContainer // must after setNavigator

        titleContainer.showDividers = LinearLayout.SHOW_DIVIDER_NONE
        titleContainer.dividerPadding = dp2px(15f).toInt()
//        titleContainer.dividerDrawable = getDrawable(R.drawable.back_down_gray_icon)
        ViewPagerHelper.bind(mViewBinding.magicIndicator, mViewBinding.viewPager)
    }

    /**
     * 创建修改简介ActivityResultLauncher
     *
     * @return
     */
    private fun createModifyNoteResultLauncher(): ActivityResultLauncher<Intent> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == SupportActivity.RESULT_OK) {
                result.data?.let {
                    val mNote: String? = it.getStringExtra("note")
                    mNote.isNullOrEmpty().no {
//                        modifyUsrInfo(null, mNote)
                        mViewBinding.tvBriefIntroduction.text = mNote
                    }
                }
            } else if (resultCode == SupportActivity.RESULT_CANCELED) {
                Log.i(BaseVMActivity.TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    override fun OnBannerClick(position: Int) {
    }

    override fun OnBannerDataClick(bean: BannerBean?, position: Int) {
        showToast(bean?.image)
    }

}